package com.chaosyeb.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chaosyeb.server.pojo.Employee;
import com.chaosyeb.server.pojo.MailConstants;
import com.chaosyeb.server.pojo.MailLog;
import com.chaosyeb.server.service.IEmployeeService;
import com.chaosyeb.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description : 邮件发送定时任务
 * @Author : Chaos
 * @Date : 2022/1/25 17:13
 * @Version : 1.0
 **/
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 邮件发送的定时任务
     * 10秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        //获取状态为0并且重试时间小于当前时间的
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));
        //对list中的每个元素执行给定的操作，直到每个元素都被操作或处理
        list.forEach(mailLog -> {
            //如果重试次数大于3，更新状态为2，投递失败，不在重试
            if (mailLog.getCount() >= MailConstants.MAX_TYPE_COUNT){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2)
                        .eq("msgId",mailLog.getMsgId()));
            }
            //否则投递失败，更新重试次数、更新时间和超时时间。
            mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount() + 1)
                    .set("updateTime",LocalDateTime.now())
                    .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msgId",mailLog.getMsgId()));
            //Employee emp = employeeService.list().get(0);
            Employee emp = employeeService.getEmployee(mailLog.getEid()).get(0);
            //发送信息
            rabbitTemplate.convertAndSend("MailConstants.MAIL_EXCHANGE_NAME", MailConstants.MAIL_ROUTING_KEY_NAME,
                    emp, new CorrelationData(mailLog.getMsgId()));
        });
    }
}
